<template>
  <div class="product_tree" v-loading="loading">
    <el-popover placement="bottom" width="340" trigger="click" style="height: 300px" :append-to-body="false">
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        :check-strictly="radio"
        :node-key="defaultProps.value"
        :default-checked-keys="value"
        default-expand-all
        :props="defaultProps"
        @check="handleCheck"
      />
      <el-input
        slot="reference"
        v-model="text"
        :placeholder="placeholder"
        readonly
        style="width: 340px"
        class="product-tree-select"
        :class="[inputClass]"
        @click.native="handleInputClick"
      >
        <i slot="suffix" class="el-input__icon el-icon-arrow-down"
      /></el-input>
    </el-popover>
  </div>
</template>

<script>
export default {
  props: {
    defaultProps: {
      type: Object,
      default: () => ({
        children: "child",
        label: "label",
        type: "",
        value: "value"
      })
    },
    value: {
      type: [Array]
    },
    defaultCheckedKeys: {
      type: Array,
      default: () => []
    },
    req: {
      type: Object,
      default: () => {}
    },
    query: {
      stype: String,
      default: ""
    },
    placeholder: {
      stype: String,
      default: "请选择"
    },
    radio: {
      type: Boolean,
      default: false
    },
    autoQuery: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      treeData: [],
      productKeys: [],
      text: "",
      loading: false,
      inputClass: ""
    }
  },
  created() {
    if (this.query && this.autoQuery) {
      this.queryOption()
    }
  },
  watch: {
    value(val) {
      if (val) {
        this.text = this.getTextByProductkeys(val)
      }
    }
  },
  methods: {
    handleCheck(data, node) {
      let productKeys = []
      const valuekey = this.defaultProps.value
      if (this.radio) {
        if (this.productKeys[0] == data[valuekey]) {
          productKeys = []
        } else {
          productKeys = [data[valuekey]]
        }
        this.$refs.tree.setCheckedNodes(productKeys)
      } else {
        const checkedProduct = node.checkedNodes.filter((item) => !item[this.defaultProps.children])
        productKeys = checkedProduct.map((item) => item[valuekey])
      }
      this.productKeys = productKeys
      this.$emit("getValue", productKeys)
      this.text = this.getTextByProductkeys(productKeys)
    },
    getTextByProductkeys(keys) {
      const showTags = {}
      keys.forEach((item) => {
        const currentNode = this.$refs.tree.getNode(item)
        let node = this.$refs.tree.getNode(item)
        if (!node) {
          return
        }
        while (node && this.category.findIndex((item) => item.value === node.data.value) === -1) {
          node = node.parent
        }
        if (!node) {
          return
        }
        if (showTags[node.label]) {
          showTags[node.label].push(currentNode.label)
        } else {
          showTags[node.label] = [currentNode.label]
        }
      })
      let text = ""

      if (this.defaultProps.type == "old") {
        for (const key in showTags) {
          text += `${key};`
        }
        if (text.length > 0) {
          text = text.substring(0, text.length - 1)
        }
        this.$emit("getOldText", text)
      } else {
        for (const key in showTags) {
          text += `${key}: ${showTags[key].join(",")}\n`
        }
      }
      return text
    },
    clearOption() {
      this.treeData = []
    },
    queryOption() {
      this.loading = true
      this.$ajax.get(this.query).then((res) => {
        this.treeData = res.data
        this.category = this.treeData.map((item) => ({ label: item.label, value: item.value }))
        this.$nextTick(() => {
          this.loading = false
          if (this.value) {
            this.text = this.getTextByProductkeys(this.value)
          }
        })
      })
    },
    handleInputClick() {
      if (this.inputClass === "") {
        this.inputClass = "is-reverse"
      } else {
        this.inputClass = ""
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url("../../styles/var.less");
.product_tree {
  /deep/.el-popover {
    max-height: 300px;
    overflow-y: auto;
  }
  /deep/.product-tree-select {
    input {
      cursor: pointer;
    }
    &.is-reverse {
      .el-input__icon {
        transform: rotate(180deg);
      }
    }
  }
  // .input {
  //   position: relative;
  //   .el-icon {
  //     position: absolute;
  //     right: 20px;
  //     top: 9px;
  //     color: #c0c4cc;
  //     font-size: 14px;
  //     transition: transform 0.3s;
  //     cursor: pointer;
  //   }
  //   &.rotate {
  //     .el-icon {
  //       transform: rotate(180deg);
  //     }
  //   }
  // }
}
</style>
